package ysq.xyg.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import ysq.weixin.util.MD5Util;
import ysq.weixin.util.weatherApi;
import ysq.xyg.model.*;
import ysq.xyg.model.User;
import ysq.xyg.model.info.UserInfo;
import ysq.xyg.model.info.UserInfo;
import ysq.xyg.model.info.Page;
import ysq.xyg.model.info.ReturnEntity;
import ysq.xyg.service.DeviceService;
import ysq.xyg.service.ProductService;
import ysq.xyg.service.UserService;
import ysq.xyg.util.BaseConstant;
import ysq.xyg.util.DateUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yu sheng qiang
 * @create 2017-04-19 14:15
 **/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    private static Logger log= LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;
    @Resource
    private ProductService productService;
    @Resource
    private DeviceService deviceService;

    private User user;

    @RequestMapping("/listPage")
    public ModelAndView List(HttpServletRequest request, HttpServletResponse response,String menuid){
        return new ModelAndView("/userList");
    }

    @RequestMapping(value = "/JsonList",method = RequestMethod.POST)
    public @ResponseBody JSONObject JsonList(User user,Page page) throws MalformedURLException, UnsupportedEncodingException {
        PageInfo<User> pageInfo=userService.pageInfo(user,page.getLimit(),page.getPage());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            for(User item:pageInfo.getList()){
                row=new JSONObject();
                row.put("openid",item.getOpenid());
                row.put("userId",item.getUserId());
                row.put("userName",item.getUserName());
                rows.add(row);
            }
            jsonObject.put("data",rows);
        }
        return jsonObject;
    }

    @RequestMapping(value = "/SelectEntity",method = RequestMethod.GET)
    public ModelAndView SelectEntity(String id){
        ModelAndView view=new ModelAndView("/userUpdateOrSave");
        user=userService.selectByPrimaryKey(id);
        view.addObject("user",user);
        return view;
    }

    //登录
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public @ResponseBody
    ReturnEntity login(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo){
        User user=userService.selectByName(userInfo.getUserName());
        if(user == null || "".equals(user)){
            return new ReturnEntity(BaseConstant.CODE_ERROR,BaseConstant.LOGIN_ERROR_NOID);
        }
        if(!(MD5Util.MD5Encode(userInfo.getUserPassword()).equalsIgnoreCase(user.getUserPassword()))){
            return new ReturnEntity(BaseConstant.CODE_ERROR,BaseConstant.LOGIN_ERROR_PSW);
        }
        if(userInfo.getAutoLogin() == BaseConstant.CODE_AUTOLOGIN_Y){
            BaseController.CookiesAddObject(request,response,BaseConstant.USER_COOKIE_LOGINNAME,userInfo.getUserName());
            BaseController.CookiesAddObject(request,response,BaseConstant.USER_COOKIE_PASSWORD,userInfo.getUserPassword());
        }else{
            BaseController.CookiesDeleteObject(request,response,BaseConstant.USER_COOKIE_LOGINNAME);
            BaseController.CookiesDeleteObject(request,response,BaseConstant.USER_COOKIE_PASSWORD);
        }
        userInfo.setOpenid(user.getOpenid());
        request.getSession().setAttribute(BaseConstant.USER_SESSION_USERINFO,userInfo);
        return new ReturnEntity(BaseConstant.CODE_SUCCESS,userInfo,"user/index");
    }
    //注册
    @RequestMapping(value="/register",method=RequestMethod.POST)
    public @ResponseBody
    ReturnEntity register(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo){
        User user=userService.selectByName(userInfo.getUserName());
        if(user != null){
            return new ReturnEntity(BaseConstant.CODE_ERROR,"用户名【"+userInfo.getUserName()+"】存在!");
        }else{
            user=new User();
            user.setUserName(userInfo.getUserName());
        }
        user.setUserPassword(MD5Util.MD5Encode(userInfo.getUserPassword()));
        user.setUserDate(DateUtil.DateToStr(new Date(),DateUtil.DATE_TIME_PATTERN));
        user.setOpenid(user.getUserName());
        int id=userService.insert(user);
        if(id<=0) {
            return new ReturnEntity(BaseConstant.CODE_ERROR, "注册失败!");
        }
        return new ReturnEntity(BaseConstant.CODE_SUCCESS,userInfo,"userLogin");
    }
    //退出
    @RequestMapping(value="/Exit",method= RequestMethod.GET)
    public String selectUser(HttpServletRequest request,Model model){
        BaseController.SessionDeleteObject(request,BaseConstant.USER_SESSION_USERINFO);
        return "redirect:/";
    }
    /**
     * 登录进入默认页面
     * */
    @RequestMapping(value="/main")
    public ModelAndView main(HttpServletRequest request,HttpServletResponse response){
        UserInfo userInfo=acceptCurrentPcUser(request);
        List<Product> deviceList=productService.listLeft(new Product(BaseConstant.PRODUCT_TYPE_JCY,userInfo.getOpenid()));
        if(deviceList!=null && deviceList.size()>0){
            for (int i=0;i<deviceList.size();i++){
                Product product=deviceList.get(i);
                Product d=productService.selectData(product);
                product.setDeviceType("2");
                d.setDeviceType("2");
                if(d!=null&&d.getTime()!=null){
                    Date deviceDate=DateUtil.getSecondOneDate(d.getTime(),60*10);
                    if(deviceDate.getTime()>new Date().getTime()){
                        d.setDeviceType("1");
                        product.setDeviceType("1");
                    }
                }
                d=PhoneController.setTip(d);
                product.setNewProduct(d);
            }
        }
        return new ModelAndView("/pcUserMain")
                .addObject("userInfo",userInfo)
                .addObject("deviceList",deviceList);
    }
    /**
     * 登录进入首页
     * */
    @RequestMapping(value="/index")
    public ModelAndView Index(HttpServletRequest request,HttpServletResponse response){
        UserInfo userInfo=acceptCurrentPcUser(request);
        return new ModelAndView("/userIndex")
                .addObject("userInfo",userInfo);
    }
    /**
     * 设备城市信息查询
     * */
    @RequestMapping(value="/selectDevice/{deviceId}")
    public ModelAndView selectDevice(HttpServletRequest request,HttpServletResponse response,@PathVariable String deviceId){
        List<Device> deviceList=deviceService.list(new Device(deviceId));
        Device device=null;
        if(deviceList!=null&&deviceList.size()>0){
            device=deviceList.get(0);
        }
        return new ModelAndView("/pcCityUpdateOrSave")
                .addObject("device",device);
    }
    /**
     * 设备添加信息查询
     * */
    @RequestMapping(value="/addDevice")
    public ModelAndView selectDevice(HttpServletRequest request,HttpServletResponse response){
        UserInfo userInfo=acceptCurrentPcUser(request);
        return new ModelAndView("/pcDeviceSave")
                .addObject("userInfo",userInfo);
    }
    /**
     * 测试仪统计
     * */
    @RequestMapping(value="/deviceEcharts")
    public @ResponseBody
    JSONObject deviceEcharts(String deviceId,String type,String code) throws IOException {
        JSONObject jsonObject=new JSONObject();
        Date newDate=new Date();
        List<String> dataList=new ArrayList<String>();
        List<Double> dayList=new ArrayList<Double>();
        if("day".equals(type)||StringUtil.isEmpty(type)){
            //天
            Product product=new Product();
            product.setDeviceId(deviceId);
            product.setStartDate(DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN)+" 00:00:00");
            product.setEndDate(DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN)+" 23:59:59");
            List<Product> dayAllList=productService.selectDataList(product);
            Date baseDate=DateUtil.getBeginDate(DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN));
            Date currentDate=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN+" "+DateUtil.DATE_HOUR)+":00:00");
            //获取今天24小时
            for(int i=0;i<24;i++){
                if(currentDate.getTime()>=DateUtil.getSecondOneDate(baseDate,60*60*i).getTime()){
                    dataList.add(i+1+"时");
                    dayList.add(PhoneController.reslutValue(dayAllList,DateUtil.getSecondOneDate(baseDate,60*60*i),DateUtil.getSecondOneDate(baseDate,60*60*(i+1)),code));
                }
            }
        }else if("month".equals(type)){
            //月
            Product product=new Product();
            product.setDeviceId(deviceId);
            product.setStartDate(DateUtil.DateToStr(newDate,DateUtil.DATE_YEARMONTH)+"-01 00:00:00");
            List<Product> dayAllList=productService.selectDataList(product);
            Date baseDate=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(newDate,DateUtil.DATE_YEARMONTH)+"-01 00:00:00");
            Date currentDate=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(newDate,DateUtil.DATE_PATTERN)+" 00:00:00");
            for(int i=0;i<31;i++){
                if(currentDate.getTime()>=DateUtil.getDateOfDate(baseDate,-i).getTime()){
                    dataList.add("第"+(i+1)+"天");
                    Date startTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(DateUtil.getDateOfDate(baseDate,-i),DateUtil.DATE_PATTERN)+" 00:00:00");
                    Date endTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,DateUtil.DateToStr(DateUtil.getDateOfDate(baseDate,-i),DateUtil.DATE_PATTERN)+" 23:59:59");
                    dayList.add(PhoneController.reslutValue(dayAllList,startTime,endTime,code));
                }
            }
        }else if("year".equals(type)){
            //周
            Product product=new Product();
            product.setDeviceId(deviceId);
            product.setStartDate(DateUtil.DateToStr(DateUtil.getDateOfDate(newDate,7),DateUtil.DATE_PATTERN)+" 00:00:00");
            product.setEndDate(DateUtil.DateToStr(DateUtil.getDateOfDate(newDate,0),DateUtil.DATE_PATTERN)+" 23:59:59");
            List<Product> dayAllList=productService.selectDataList(product);
            for(int i=0;i<7;i++){
                int z=7-i;
                String baseDate=DateUtil.DateToStr(DateUtil.getDateOfDate(newDate,z),DateUtil.DATE_PATTERN);
                dataList.add(baseDate);
                Date startTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,baseDate+" 00:00:00");
                Date endTime=DateUtil.strToDate(DateUtil.DATE_TIME_PATTERN,baseDate+" 23:59:59");
                dayList.add(PhoneController.reslutValue(dayAllList,startTime,endTime,code));
            }
        }
        jsonObject.put("dayList",dayList);
        jsonObject.put("dataList",dataList);
        return jsonObject;
    }
}
